use reqwest::{blocking::get, header::ETAG};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;

fn main() {
    let url =
        "https://raw.githubusercontent.com/yescallop/areacodes/refs/heads/master/sql/codes.sql";

    let path = Path::new("src/data.rs");

    println!("cargo:rerun-if-changed={}", path.display());
    println!("cargo:rerun-if-changed=build.rs");

    let response = get(url).expect("GitHub cannot be accessed! ");
    let etag = response
        .headers()
        .get(ETAG)
        .map(|v| v.to_str().unwrap())
        .unwrap()
        .to_string();

    if path.exists() {
        let file = File::open(path).unwrap();
        let mut reader = BufReader::new(file);
        let mut local_etag = String::new();
        reader.read_line(&mut local_etag).ok();
        local_etag = local_etag.trim().to_string();
        if local_etag == format!("// {}", etag) {
            println!("Successfully updated!");
            return;
        }
    }

    let mut map = HashMap::new();
    let area_codes = response.text().unwrap();
    let mut area_codes = area_codes.lines();
    area_codes.next();
    for line in area_codes {
        let mut line = line.trim().to_string();
        line = line.replace("(", "");
        line = line.replace("),", "");
        line = line.replace("0000", "");
        line = line.replace("'", "");
        let mut area: Vec<String> = line.split(",").map(|s| s.to_string()).collect();
        if area[0].len() == 6 && &area[0][4..] == "00" {
            area[0] = area[0][..4].to_string();
        }
        if !map.contains_key(&area[0].parse::<u32>().unwrap()) {
            map.insert(area[0].parse::<u32>().unwrap(), area[1].trim().to_string());
        }
    }

    let area_codes_supplement: Vec<(u32, &str)> = vec![
        (1101, "市辖区"),
        (1201, "市辖区"),
        (3101, "市辖区"),
        (4190, "省直辖县级行政区划"),
        (4290, "省直辖县级行政区划"),
        (4690, "省直辖县级行政区划"),
        (5001, "市辖区"),
        (5002, "县"),
        (6590, "自治区直辖县级行政区划"),
    ];
    
    for (code, name) in area_codes_supplement {
        map.insert(code, name.to_string());
    }

    let mut file = BufWriter::new(File::create(&path).unwrap());
    writeln!(&mut file, "// {}", etag).expect("Failed to write to `src/lib.rs`");
    write!(&mut file, "&[").expect("Failed to write to `src/lib.rs`");
    for (key, value) in map {
        write!(&mut file, "({}, {:?}),", key, value).expect("Failed to write to `src/lib.rs`");
    }
    writeln!(&mut file, "]").expect("Failed to write to `src/lib.rs`");

}
